<template>
  <div class="ads-management">
    <!-- 操作栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索广告名称"
        clearable
        style="width: 180px"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
        v-model="searchStatus"
        placeholder="审核状态"
        clearable
        style="width: 140px"
      >
        <el-option label="待审核" :value="0" />
        <el-option label="已审核" :value="1" />
        <el-option label="投放中" :value="2" />
        <el-option label="已完成" :value="3" />
        <el-option label="已拒绝" :value="4" />
      </el-select>

      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>重置
      </el-button>
      <el-button type="success" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>新增
      </el-button>
    </div>

    <!-- 广告列表 -->
    <el-card shadow="never" class="ads-list">
      <el-table
      v-loading="loading"
      :data="adsList"
      style="width: 100%"
      border
      stripe
    >
        <el-table-column prop="id" label="广告ID" width="80" />
        <el-table-column prop="title" label="广告标题" min-width="150" />
        <el-table-column prop="advertiserName" label="广告主" min-width="120" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="投放开始时间" min-width="150">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="投放结束时间" min-width="150">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
 <el-table-column label="操作" width="280" fixed="right">
  <template #default="{ row }">
    <el-button-group>
      <el-button
        type="primary"
        size="small"
        @click="viewAdsDetail(row)"
      >
        <el-icon><View /></el-icon>详情
      </el-button>
      <el-button
        type="warning"
        size="small"
        @click="openEditDialog(row)"
      >
        <el-icon><Edit /></el-icon>编辑
      </el-button>
      <el-dropdown
        v-if="row.status === 0"
        trigger="click"
        @command="(command) => handleAudit(command, row)"
      >
        <el-button type="primary" size="small">
          <el-icon><Document /></el-icon>审核
          <el-icon class="el-icon--right"><ArrowDown /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="approve">
              <el-icon><Check /></el-icon>通过广告
            </el-dropdown-item>
            <el-dropdown-item command="reject" divided>
              <el-icon><Close /></el-icon>拒绝广告
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button
        type="danger"
        size="small"
        @click="handleDelete(row)"
      >
        <el-icon><Delete /></el-icon>删除
      </el-button>
    </el-button-group>
  </template>
</el-table-column>
      </el-table>

      <!-- 分页 -->
         <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </el-card>

    <!-- 广告表单 -->
 <el-dialog
  :title="dialogType === 'create' ? '添加广告' : '编辑广告'"
  v-model="dialogVisible"
  width="600px"
>
  <el-form
    ref="adsFormRef"
    :model="adsForm"
    :rules="adsRules"
    label-width="120px"
    label-position="right"
  >
    <el-form-item label="广告标题" prop="title">
      <el-input v-model="adsForm.title" placeholder="请输入广告标题" />
    </el-form-item>
    
    <el-form-item label="广告内容" prop="content">
      <el-input
        v-model="adsForm.content"
        type="textarea"
        :rows="5"
        placeholder="请输入广告内容"
      />
    </el-form-item>
    
    <el-form-item label="投放时间" prop="dateRange">
      <el-date-picker
        v-model="adsForm.dateRange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        :default-time="defaultTime"
      />
    </el-form-item>
    
    <el-form-item label="预算金额" prop="budget">
      <el-input-number
        v-model="adsForm.budget"
        :min="0.01"
        :precision="2"
        :step="100"
        controls-position="right"
      />
      <span class="budget-unit">元</span>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitAdsForm">确定</el-button>
    </span>
  </template>
</el-dialog>

    广告详情抽屉
 <el-drawer
  v-model="drawerVisible"
  title="广告详情"
  size="50%"
  destroy-on-close
>
  <template v-if="currentAds">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="广告ID" width="150px">
        {{ currentAds.id }}
      </el-descriptions-item>
      <el-descriptions-item label="广告标题">
        {{ currentAds.title }}
      </el-descriptions-item>
      <el-descriptions-item label="广告主">
        {{ currentAds.advertiserName }}
      </el-descriptions-item>
      <el-descriptions-item label="广告状态">
        <el-tag :type="getStatusType(currentAds.status)">
          {{ getStatusText(currentAds.status) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="投放开始时间">
        {{ formatDateTime(currentAds.startTime) }}
      </el-descriptions-item>
      <el-descriptions-item label="投放结束时间">
        {{ formatDateTime(currentAds.endTime) }}
      </el-descriptions-item>
      <el-descriptions-item label="预算金额">
        ¥{{ currentAds.budget?.toFixed(2) || '0.00' }}
      </el-descriptions-item>
      <el-descriptions-item label="广告主ID">
        {{ currentAds.advertiserId }}
      </el-descriptions-item>
      <el-descriptions-item label="广告内容" :span="2">
        {{ currentAds.content }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ formatDateTime(currentAds.createdTime) }}
      </el-descriptions-item>
      <el-descriptions-item label="更新时间">
        {{ formatDateTime(currentAds.updatedTime) }}
      </el-descriptions-item>
    </el-descriptions>
  </template>
</el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userInfo } from '@/api/userControl'
import {
  getAdvertisementList,
  getAdvertisementDetail,
  createAdvertisement,
  updateAdvertisement,
  deleteAdvertisement,
  approveAdvertisement,
  rejectAdvertisement
} from '@/api/advertisement'
import {
  Plus,
  Search,
  View,
  Edit,
  Delete,
  Check,
  Close,
  Refresh,
  Document,
  ArrowDown
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
const router = useRouter()
// 状态管理
const loading = ref(false)
const adsList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogType = ref('create')
const drawerVisible = ref(false)
const currentAds = ref(null)
const searchStatus = ref(null)
// 默认时间配置
const defaultTime = [
  new Date(2000, 1, 1, 9, 0, 0),
  new Date(2000, 1, 1, 18, 0, 0)
]
// 表单相关
const adsFormRef = ref(null)
const adsForm = reactive({
  title: '',
  content: '',
  dateRange: [],
  budget: 0.01
})


// 表单验证规则
const adsRules = {
  title: [
    { required: true, message: '请输入广告标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入广告内容', trigger: 'blur' },
    { min: 10, message: '至少输入10个字符', trigger: 'blur' }
  ],
  dateRange: [
    { required: true, message: '请选择投放时间', trigger: 'change' }
  ],
  budget: [
    { required: true, message: '请输入预算金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ]
}

// 状态映射
const statusMap = {
  0: { text: '待审核', type: 'warning' },
  1: { text: '已审核', type: 'success' },
  2: { text: '投放中', type: 'danger' },
  3: { text: '已完成', type: 'success' },
  4: { text: '已拒绝', type: 'danger' }
}

const getStatusText = (status) => statusMap[status]?.text || '未知状态'
const getStatusType = (status) => statusMap[status]?.type || 'info'

// 初始化
onMounted(() => {
  fetchAdsList()
})
// 重置
const handleReset = () => {
  searchQuery.value = ''
  searchStatus.value = null
  handleSearch()
}
// 获取广告列表
const fetchAdsList = async () => {
  loading.value = true
  try {
    const res = await getAdvertisementList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchQuery.value,
      status: searchStatus.value
    })
    console.log(res)
    if (res.data.code === 200) {
      const advertisements = res.data.data.records

      const advertiserPromises = advertisements.map(ad => 
        userInfo(ad.advertiserId)
          .then(userRes => {
            if (userRes.data.code === 200) {
              return {
                id: ad.advertiserId,
                username: userRes.data.data.username
              }
            }
            return {
              id: ad.advertiserId,
              username: '未知用户'
            }
          })
          .catch(() => ({
            id: ad.advertiserId,
            username: '未知用户'
          }))
      )
      
      const advertisers = await Promise.all(advertiserPromises)
      
      adsList.value = advertisements.map(ad => ({
        ...ad,
        advertiserName: advertisers.find(advertiser => 
          advertiser.id === ad.advertiserId
        )?.username || '未知用户'
      }))

      total.value = res.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取广告列表失败')
  } finally {
    loading.value = false
  }
}

// 查看广告详情
const viewAdsDetail = (ads) => {
  // adId.value = ads.id
  // currentAds.value = ads
  // drawerVisible.value = true
  router.push(`/admin/ad-detail/${ads.id}`)
}

// 查看详情
// const viewAdDetails = (id) => {
//     router.push(`/advertiser/ad-details/${id}`)
// }

// 打开创建对话框
const openCreateDialog = () => {
  dialogType.value = 'create'
  adsForm.title = ''
  adsForm.content = ''
  adsForm.timeRange = []
  adsForm.budget = 0
  dialogVisible.value = true
}


// 打开编辑对话框
const openEditDialog = async (ads) => {
  dialogType.value = 'edit'
  try {
    loading.value = true
    const res = await getAdvertisementDetail(ads.id)
    if (res.data.code === 200) {
      const data = res.data.data
      Object.assign(adsForm, {
        id: data.id,
        title: data.title,
        content: data.content,
        dateRange: [data.startTime, data.endTime],
        budget: data.budget
      })
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取广告详情失败')
  } finally {
    loading.value = false
    dialogVisible.value = true
  }
}

// 修改提交表单方法
const submitAdsForm = async () => {
  if (!adsFormRef.value) return
  
  try {
    await adsFormRef.value.validate()
    
    const params = {
      title: adsForm.title,
      content: adsForm.content,
      startTime: adsForm.dateRange[0],
      endTime: adsForm.dateRange[1],
      budget: adsForm.budget
    }

    if (dialogType.value === 'create') {
      const res = await createAdvertisement(params)
      if (res.data.code === 200) {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        fetchAdsList()
      } else {
        ElMessage.error(res.data.message || '创建失败')
      }
    } else {
      const res = await updateAdvertisement(adsForm.id, params)
      if (res.data.code === 200) {
        ElMessage.success('修改成功')
        dialogVisible.value = false
        fetchAdsList()
      } else {
        ElMessage.error(res.data.message || '修改失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}
// 拒绝广告
const handleReject = (ads) => {
  ElMessageBox.confirm(
    '确定要拒绝该广告吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await rejectAdvertisement(ads.id)
      ElMessage.success('已拒绝该广告')
      fetchAdsList()
    } catch (error) {
      ElMessage.error('操作失败')
    }
  }).catch(() => {})
}
const handleAudit = (command, row) => {
  if (command === 'approve') {
    handleApprove(row)
  } else if (command === 'reject') {
    handleReject(row)
  }
}
// 审核广告
const handleApprove = (ads) => {
  ElMessageBox.confirm(
    '确定要通过该广告吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await approveAdvertisement(ads.id)
      ElMessage.success('审核通过成功')
      fetchAdsList()
    } catch (error) {
      ElMessage.error('操作失败')
    }
  }).catch(() => {})
}


// 修改删除广告方法
const handleDelete = (ads) => {
  ElMessageBox.confirm(
    '确定要删除该广告吗？此操作不可恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteAdvertisement(ads.id)
      ElMessage.success('删除成功')
      fetchAdsList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAdsList()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAdsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAdsList()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未知'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}
</script>

<style scoped>
.ads-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 抽屉样式 */
:deep(.el-descriptions__label) {
  width: 150px;
  font-weight: bold;
}

:deep(.el-descriptions__content) {
  word-break: break-all;
}

:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-dropdown .el-icon--right) {
  margin-left: 4px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 5px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
  }

  .search-bar .el-input,
  .search-bar .el-select {
    width: 100% !important;
  }

  .search-bar .el-button {
    width: 100%;
  }
}
</style>